package controller;

import domain.Cliente;
import java.sql.SQLException;
import repository.ClienteDAO;

public class ClienteController {
    
    public ClienteDAO dao;
    
    public void adicionarCliente(Cliente c) throws SQLException{
        String dataNasc;
        dataNasc = c.getDataNasc().getYear() + 1900 + "-";
        dataNasc += c.getDataNasc().getMonth() + 1 + "-";
        dataNasc += c.getDataNasc().getDate();
        String sql = "insert into cliente values(";
        sql += "'" + c.getCpf()+ "',";
        sql += "'" + dataNasc + "',";
        sql += "'" + c.getNome() + "',";
        sql += "'" + c.getTelefone()+ "',";
        sql += "now(),";
        sql += "'" + c.getEmail() + "');";
        this.dao = new ClienteDAO();
        this.dao.save(sql);
    }

    public void buscarCliente(String text) throws SQLException {
        String sql;
        if(text.isEmpty()){
            sql = "select * from cliente;";
        }else{
            sql = "select * from cliente where upper(nome) like '%" + text.toUpperCase() + "%';";
        }
        
        this.dao = new ClienteDAO();
        this.dao.read(sql);
    }

    public void removerCliente(String id) throws SQLException {
        String sql = "delete from cliente where cpf like '" + id + "';";
        new ClienteDAO().delete(sql);
    }

    public void buscarIdCliente(String id) throws SQLException {
        String sql = "select * from cliente where cpf like '" + id + "';";
        dao = new ClienteDAO();
        dao.buscarIdCliente(sql);
    }
    
    public void buscarIdClienteConta(String id) throws SQLException {
        String sql;
        if(id.isEmpty()){
            sql = "select * \n" +
                        "from cliente \n" +
                        "where cpf NOT IN (SELECT cpf FROM conta_cliente);";
        }else{
            sql = "select *\n" +
                        "from cliente \n" +
                        "where upper(nome) like '%" + id.toUpperCase() + "%' and cpf NOT IN (SELECT cpf FROM conta_cliente);";
        }
        dao = new ClienteDAO();
        dao.read(sql);
    }

    public void alterarCliente(Cliente c) throws SQLException {
        String dataNasc;
        dataNasc = c.getDataNasc().getYear() + 1900 + "-";
        dataNasc += c.getDataNasc().getMonth() + 1 + "-";
        dataNasc += c.getDataNasc().getDate();
        String sql = "update cliente set ";
        sql += "cpf = '" + c.getCpf()+ "',";
        sql += "datanascimento = '" + dataNasc + "',";
        sql += "nome = '" + c.getNome() + "',";
        sql += "telefone = '" + c.getTelefone()+ "',";
        sql += "email = '" + c.getEmail() + "'";
        sql += "where cpf like '" + c.getCpf()+"';";
        this.dao = new ClienteDAO();
        this.dao.update(sql);
    }
}
